﻿using DotNetty.Buffers;
using DotNetty.Codecs;
using DotNetty.Common.Utilities;
using DotNetty.Transport.Channels;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using InkjetControl.NLog;

namespace InkjetControl.codec.codes
{
    public class MessageEncoder : MessageToByteEncoder<Message>
    {
        protected override void Encode(IChannelHandlerContext context, Message message, IByteBuffer output)
        {
            if (message.MessageType != MessageType.EMPTY)
            {
                if (message.SessionId <= 0)
                {
                    message.SessionId = SessionIdGenerator.SessionID;
                }
                int bodySize = 0;
                string body = null;
                if (message.Body != null)
                {
                    body = JsonConvert.SerializeObject(message.Body, Formatting.None);
                    bodySize = Encoding.UTF8.GetByteCount(body);
                    Log.Logger.Debug("MessageEncoder body:{0}, bodySize:{1}", body, bodySize);
                }

                output = output
                // 魔数
                .WriteInt(Constants.MAGIC_NUMBER)
                // 主版本号
                .WriteByte(Constants.MAIN_VERSION)
                // 次版本号
                .WriteByte(Constants.SUB_VERSION)
                // 修改版本号
                .WriteByte(Constants.MODIFY_VERSION)
                // 写入 session id
                .WriteLong(message.SessionId)
                // 消息类型
                .WriteByte((byte)message.MessageType);

                //
                if (string.IsNullOrEmpty(message.MachineCode))
                {
                    output.WriteInt(0);
                }
                else
                {
                    output.WriteInt(Encoding.UTF8.GetByteCount(message.MachineCode));
                    output.WriteString(message.MachineCode, Encoding.UTF8);
                }

                if (string.IsNullOrEmpty(message.MachineLabel))
                {
                    output.WriteInt(0);
                }
                else
                {
                    int mlLen = Encoding.UTF8.GetByteCount(message.MachineLabel); 
                    output.WriteInt(mlLen);                   
                    output.WriteString(message.MachineLabel, Encoding.UTF8);
                }


                // body size
                output.WriteInt(bodySize);
                // body
                if (body != null)
                {
                    //_ = output.WriteString(body, Encoding.UTF8);
                    output.WriteBytes(Encoding.UTF8.GetBytes(body));
                }

            }
        }
    }


}
